import React, { useEffect, useState } from 'react';
import Web3 from 'web3';
import { useParams, Link } from 'react-router-dom';
import { Rate, Upload, Button, message } from 'antd';
import MarketplaceABI from '../contract/ABIs/Marketplace.json'; // 用户列表合约 ABI
import MaterialListAddr from '../contract/ADDRESSes/MaterialListAddr';
import './transactionHistory.css'; // 添加样式文件

const BuyerReview = () => {
    // 使用 useParams 获取路由参数中的地址信息
    const { userAddr } = useParams();
    const [SellerProductListS, setSellerProductListS] = useState([]);
    const [accounts1, setAccounts1] = useState('');
    const [isLoading, setIsLoading] = useState(true); // 新增状态用于标识数据是否加载完成

    const web3 = new Web3(window.ethereum);
    const marketplaceContract = new web3.eth.Contract(MarketplaceABI, MaterialListAddr);

    useEffect(() => {
        const fetchTransactions = async () => {
            try {
                const SellerProductListS = [];
                const accounts = await web3.eth.requestAccounts();
                setAccounts1(accounts[0]);

                // 获取所有商品id
                const SellerProductIds = await marketplaceContract.methods.getSellerProductIds().call({ from: accounts[0] });

                // 获取已购买的商品id
                const TransactionHistoryList = await marketplaceContract.methods.viewTransactionHistory().call({ from: accounts[0] });
                console.log("TransactionHistoryList", TransactionHistoryList);

                // 获取商品的所有评价信息
                for (const key of SellerProductIds) {
                    const SellerProductList = await marketplaceContract.methods.getSellerReviews(key).call({ from: accounts[0] });
                    for (const SellerProduct of SellerProductList) {
                        SellerProductListS.push(SellerProduct);
                    }
                }
                for (const key of TransactionHistoryList) {
                    const BuyerReviews = await marketplaceContract.methods.getBuyerReviews(key.productId).call({ from: accounts[0] });
                    for (const BuyerReview of BuyerReviews) {
                        SellerProductListS.push(BuyerReview);
                    }
                }
                console.log("transactions", SellerProductListS);
                setSellerProductListS(SellerProductListS);
                setIsLoading(false); // 数据加载完成
            } catch (error) {
                console.error("Error fetching transactions:", error);
                setIsLoading(false); // 数据加载完成，即使出现错误
            }
        };
        fetchTransactions();
    }, [userAddr]);

    if (isLoading) {
        return <div>加载中...</div>; // 加载时显示的内容
    }

    return (
        <div className="transaction-history-container">
            <h2 className="page-title">你商品的所有评价</h2>
            <div className="transactions-list">
                {SellerProductListS.map((SellerProduct, index) => (
                    <div key={index} className="transaction-item">
                        <div className="transaction-details">
                            {((SellerProduct.reviewer || '').trim().toLowerCase() === (accounts1 || '').trim().toLowerCase()) && (
                                <h3 className="transaction-name">卖家对您的评价</h3>
                            )}
                            <p className="transaction-quantity">评价内容: {SellerProduct.comment}</p>
                            <p className="transaction-timestamp">时间: {new Date(Number(SellerProduct.timestamp) * 1000).toLocaleString()}</p>
                            <p><strong>评分:</strong> <Rate value={Number(SellerProduct.rating)} style={{ fontSize: '24px' }} disabled /> </p>
                        </div>
                        <div className="transaction-image">
                            <img src={`https://ipfs.infura.io/ipfs/${SellerProduct.ipfsHash}`} alt={SellerProduct.name} />
                        </div>
                        <div className="transaction-actions">
                            <Link to={`/index1/${userAddr}/SubmitReview/${SellerProduct.productId}/mai2`} className="review-button">评价买家</Link>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
};

export default BuyerReview;
